<template>
  <div class="quiz-page" v-loading="loading" element-loading-text="加载中...">
    <!-- 测验标题 -->
    <el-card shadow="never" class="quiz-header-card">
      <div class="header-content">
        <div class="title-section">
          <div class="title-row">
            <el-button 
              icon="el-icon-arrow-left" 
              circle 
              size="small"
              @click="$router.back()"
            ></el-button>
            <h1 class="quiz-title">{{ quiz.title }}</h1>
          </div>
          <p class="quiz-meta">共{{ quiz.questions.length }}题</p>
        </div>
        
        <div class="timer-section">
          <i class="el-icon-time"></i>
          <span :class="['timer-text', { warning: timeRemaining < 300 }]">
            {{ formatTime(timeRemaining) }}
          </span>
        </div>
      </div>
    </el-card>

    <!-- 题目导航 -->
    <el-card shadow="never" class="nav-card">
      <p class="nav-title">题目导航</p>
      <div class="question-nav">
        <button
          v-for="(q, index) in quiz.questions"
          :key="index"
          :class="[
            'nav-button',
            { active: currentQuestionIndex === index },
            { answered: answers[index] !== null && answers[index] !== undefined && (Array.isArray(answers[index]) ? answers[index].length > 0 : true) }
          ]"
          @click="currentQuestionIndex = index"
        >
          {{ index + 1 }}
        </button>
      </div>
    </el-card>

    <!-- 测验题目 -->
    <el-card shadow="never" class="question-card">
      <div v-if="!loading && currentQuestion" class="question-container">
        <div class="question-item">
          <div class="question-header">
            <span class="question-badge">{{ currentQuestionIndex + 1 }}</span>
            <div class="question-info">
              <p class="question-title">
                {{ currentQuestionIndex + 1 }}. {{ currentQuestion.title }}
              </p>
              <p class="question-meta">
                ({{ getQuestionTypeText(currentQuestion.type) }} | {{ currentQuestion.score }}分)
              </p>
            </div>
          </div>

          <div class="options-container">
            <!-- 单选题和判断题 -->
            <el-radio-group 
              v-if="currentQuestion.type === 'single' || currentQuestion.type === 'boolean'" 
              :value="answers[currentQuestionIndex]"
              @input="updateAnswer(currentQuestionIndex, $event)"
              :disabled="isSubmitted"
              class="options-list"
            >
              <div 
                v-for="option in currentQuestion.options" 
                :key="option.key"
                class="option-label"
              >
                <el-radio :label="option.key" :disabled="isSubmitted" class="option-radio">
                  {{ option.key }}. {{ option.text }}
                </el-radio>
              </div>
            </el-radio-group>

            <!-- 多选题 -->
            <el-checkbox-group 
              v-else-if="currentQuestion.type === 'multiple'" 
              :value="answers[currentQuestionIndex]"
              @input="updateAnswer(currentQuestionIndex, $event)"
              :disabled="isSubmitted"
              class="options-list"
            >
              <div 
                v-for="option in currentQuestion.options" 
                :key="option.key"
                class="option-label"
              >
                <el-checkbox :label="option.key" :disabled="isSubmitted" class="option-checkbox">
                  {{ option.key }}. {{ option.text }}
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>

        <!-- 导航按钮 -->
        <div class="question-footer">
          <div class="nav-buttons">
            <el-button 
              :disabled="currentQuestionIndex === 0"
              @click="currentQuestionIndex--"
            >
              上一题
            </el-button>
            <el-button 
              v-if="currentQuestionIndex < quiz.questions.length - 1"
              @click="currentQuestionIndex++"
            >
              下一题
            </el-button>
          </div>

          <el-button 
            type="primary"
            :disabled="isSubmitted"
            @click="showSubmitDialog = true"
          >
            {{ isSubmitted ? '已提交' : '提交测验' }}
          </el-button>
        </div>
      </div>
      
      <!-- 空状态提示 -->
      <el-empty 
        v-if="!loading && (!quiz.questions || quiz.questions.length === 0)" 
        description="暂无题目"
      ></el-empty>
    </el-card>

    <!-- 提交确认对话框 -->
    <el-dialog
      title=""
      :visible.sync="showSubmitDialog"
      width="400px"
      center
    >
      <div class="confirm-content">
        <div class="confirm-icon">
          <i class="el-icon-question"></i>
        </div>
        <h3 class="confirm-title">确认提交测验?</h3>
        <p class="confirm-message">提交后将无法修改答案,是否确认提交?</p>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSubmitDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认提交</el-button>
      </span>
    </el-dialog>

    <!-- 测验结果对话框 -->
    <el-dialog
      title="测验结果"
      :visible.sync="showResultDialog"
      :width="resultDialogWidth"
      top="5vh"
      :close-on-click-modal="false"
      :show-close="true"
      :fullscreen="isMobile"
      custom-class="result-dialog"
    >
      <div class="result-content">
        <div class="result-summary">
          <div class="score-circle">
            <span class="score-number">{{ score }}</span>
            <span class="score-unit">分</span>
          </div>
          <p class="result-message">{{ score >= 80 ? '恭喜您通过了本章测验' : '未通过测验,请继续努力' }}</p>
        </div>

        <div class="result-stats">
          <div class="stat-row">
            <span class="stat-label">总题数</span>
            <span class="stat-value">{{ quiz.questions.length }}题</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">做对题数</span>
            <span class="stat-value" style="color: #00B42A">{{ correctCount }}题</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">正确率</span>
            <span class="stat-value">{{ accuracy }}%</span>
          </div>
        </div>

        <div class="toggle-details">
          <el-button 
            type="text" 
            @click="showDetails = !showDetails"
          >
            查看答题详情
            <i :class="['el-icon-arrow-down', { rotate: showDetails }]"></i>
          </el-button>
        </div>

        <transition name="el-zoom-in-top">
          <div v-show="showDetails" class="answer-details">
            <div 
              v-for="(question, index) in quiz.questions" 
              :key="index"
              class="detail-item"
            >
              <div class="detail-header">第{{ index + 1 }}题</div>
              <div class="detail-body">
                <p class="detail-question">{{ question.title }}</p>
                
                <div class="detail-answer">
                  <span :class="['user-answer', { correct: isCorrect(index), wrong: !isCorrect(index) }]">
                    您的答案: {{ getUserAnswerText(index, question) }}
                  </span>
                </div>
                
                <div class="detail-answer">
                  <span>正确答案: {{ formatAnswer(question.answer) }}</span>
                </div>

                <div v-if="question.explanation" class="answer-explanation">
                  <p class="explanation-title">答案解释:</p>
                  <p class="explanation-text">{{ question.explanation }}</p>
                </div>
              </div>
            </div>
          </div>
        </transition>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="returnToCourse">返回课程</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Quiz',
  data() {
    return {
      currentQuestionIndex: 0,
      answers: [],
      timeRemaining: 0,
      timer: null,
      showSubmitDialog: false,
      showResultDialog: false,
      showDetails: false,
      score: 0,
      correctCount: 0,
      windowWidth: window.innerWidth,
      loading: false,
      courseId: null,
      paperId: null,
      isSubmitted: false, // 标记是否已提交
      quiz: {
        title: '',
        timeLimit: 60, // 分钟
        questions: []
      },
      wrongQuestions: [] // 答错的题目列表
    }
  },
  watch: {
    answers: {
      handler(newVal) {
      },
      deep: true
    }
  },
  computed: {
    currentQuestion() {
      return this.quiz.questions[this.currentQuestionIndex]
    },
    accuracy() {
      if (!this.quiz.questions || this.quiz.questions.length === 0) return 0
      return Math.round((this.correctCount / this.quiz.questions.length) * 100)
    },
    isMobile() {
      return this.windowWidth <= 768
    },
    resultDialogWidth() {
      if (this.windowWidth <= 768) {
        return '100%'
      } else if (this.windowWidth <= 1024) {
        return '90%'
      } else {
        return '700px'
      }
    }
  },
  mounted() {
    // 从路由获取 courseId 和 paperId
    this.courseId = this.$route.query.courseId
    this.paperId = this.$route.params.id
    
    if (!this.courseId || !this.paperId) {
      this.$message.error('参数错误')
      this.$router.back()
      return
    }
    
    // 直接加载试卷（不检查是否已完成，由提交后的状态控制）
    this.getPaperDetail()
    
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    clearInterval(this.timer)
    window.removeEventListener('resize', this.handleResize)
  },
  computed: {
    currentQuestion() {
      return this.quiz.questions[this.currentQuestionIndex]
    },
    accuracy() {
      return Math.round((this.correctCount / this.quiz.questions.length) * 100)
    },
    isMobile() {
      return this.windowWidth <= 768
    },
    resultDialogWidth() {
      if (this.windowWidth <= 768) {
        return '100%'
      } else if (this.windowWidth <= 1024) {
        return '90%'
      } else {
        return '700px'
      }
    }
  },
  methods: {
    // 获取试卷详情
    async getPaperDetail() {
      this.loading = true
      try {
        const res = await this.$api.exam.getPaperDetail({
          course_id: this.courseId,
          paper_id: this.paperId
        })
        
        
        // 后端返回的是Paper模型,包含name/questions等字段
        const questions = (res.questions || []).map((q, index) => {
          // 解析 options JSON 字符串
          let options = []
          try {
            const parsedOptions = JSON.parse(q.options || '[]')
            // 将字符串数组转换为 {key, text} 格式
            options = parsedOptions.map((opt, i) => {
              // 格式: "A.正确" 或 "正确"
              const match = opt.match(/^([A-Z])\.(.+)$/)
              if (match) {
                return { key: match[1], text: match[2] }
              } else {
                // 如果没有选项字母，自动生成
                const key = String.fromCharCode(65 + i) // A, B, C, D...
                return { key, text: opt }
              }
            })
          } catch (e) {
            options = []
          }
          
          return {
            id: q.id,
            type: this.mapQuestionType(q.type),
            title: q.content, // 后端字段是content而非title
            score: 10, // 后端没有返回单题分数,平均分配
            options: options,
            answer: '', // 后端隐藏了正确答案
            explanation: q.explanation || ''
          }
        })
        
        this.quiz = {
          title: res.name || '试卷',
          timeLimit: res.duration || 60, // 使用后端返回的 duration 字段（分钟）
          totalScore: 100,
          questions: questions
        }
        
        
        // 初始化答题
        this.initQuiz()
      } catch (error) {
        this.$message.error('获取试卷失败')
        this.$router.back()
      } finally {
        this.loading = false
      }
    },
    
    // 映射题目类型:后端 1=单选 2=多选 3=判断 -> 前端 single/multiple/boolean
    mapQuestionType(type) {
      const typeMap = {
        1: 'single',
        2: 'multiple',
        3: 'boolean'
      }
      return typeMap[type] || 'single'
    },
    
    // 获取题目类型文本
    getQuestionTypeText(type) {
      const typeTextMap = {
        'single': '单选题',
        'multiple': '多选题',
        'boolean': '判断题'
      }
      return typeTextMap[type] || '未知类型'
    },
    
    handleResize() {
      this.windowWidth = window.innerWidth
    },
    
    // 更新答案（确保响应式）
    updateAnswer(index, value) {
      this.$set(this.answers, index, value)
    },
    
    initQuiz() {
      this.answers = this.quiz.questions.map(q => q.type === 'multiple' ? [] : null)
      this.timeRemaining = this.quiz.timeLimit * 60
      this.startTimer()
    },
    startTimer() {
      this.timer = setInterval(() => {
        if (this.timeRemaining > 0) {
          this.timeRemaining--
        } else {
          this.$message.warning('时间到!将自动提交测验')
          setTimeout(() => {
            this.submitQuiz()
          }, 1500)
        }
      }, 1000)
    },
    formatTime(seconds) {
      const m = Math.floor(seconds / 60)
      const s = seconds % 60
      return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
    },
    handleSubmit() {
      this.showSubmitDialog = false
      this.submitQuiz()
    },
    async submitQuiz() {
      if (this.timer) {
        clearInterval(this.timer)
      }
      
      try {
        
        // 格式化答案数据为对象格式 {question_id: answer}
        // 需要将选项字母（A、B、C）转换为选项文本（正确、错误等）
        const answersObj = {}
        this.quiz.questions.forEach((question, index) => {
          let answer = this.answers[index]
          
            type: question.type,
            rawAnswer: answer,
            isArray: Array.isArray(answer),
            isNull: answer === null,
            isUndefined: answer === undefined
          })
          
          // 多选题：将字母数组转为文本数组，再用逗号连接
          if (question.type === 'multiple' && Array.isArray(answer) && answer.length > 0) {
            const answerTexts = answer.map(key => {
              const option = question.options.find(opt => opt.key === key)
              return option ? option.text : key
            })
            answer = answerTexts.join(',')
            answersObj[question.id] = answer
          }
          // 判断题和单选题：将字母转为文本
          else if ((question.type === 'boolean' || question.type === 'single') && answer) {
            const option = question.options.find(opt => opt.key === answer)
            const answerText = option ? option.text : answer
            answersObj[question.id] = answerText
          }
          else {
          }
        })
        
        
        // 提交答案 - 使用对象格式传参
        const res = await this.$api.exam.submitPaper({
          course_id: this.courseId,
          paper_id: this.paperId,
          answers: answersObj
        })
        
        
        // 使用后端返回的成绩和错题详情
        this.score = res.score
        this.correctCount = res.correct_count
        
        // 使用后端返回的所有题目正确答案（字母格式）
        const correctAnswersMap = res.correct_answers || {}
        
        // 处理错题列表
        if (res.wrong_questions && res.wrong_questions.length > 0) {
          this.wrongQuestions = res.wrong_questions.map(wq => {
            // 解析选项
            let options = []
            try {
              const parsedOptions = JSON.parse(wq.options || '[]')
              options = parsedOptions.map((opt, i) => {
                const match = opt.match(/^([A-Z])\.(.+)$/)
                if (match) {
                  return { key: match[1], text: match[2] }
                } else {
                  const key = String.fromCharCode(65 + i)
                  return { key, text: opt }
                }
              })
            } catch (e) {
            }
            
            return {
              id: wq.question_id,
              text: wq.question_content,
              type: this.mapQuestionType(wq.question_type),
              options: options,
              userAnswer: wq.student_answer,
              correctAnswer: wq.correct_answer,
              explanation: wq.explanation || '暂无解析'
            }
          })
        } else {
          this.wrongQuestions = []
        }
        
        // 将后端返回的正确答案（字母格式）转换为文本格式并更新到题目中
        this.quiz.questions.forEach((question) => {
          const correctAnswerLetter = correctAnswersMap[question.id]
          if (correctAnswerLetter) {
            // 将字母转换为文本
            if (correctAnswerLetter.includes(',')) {
              // 多选题：A,B,C -> 正确,错误,其他
              const letters = correctAnswerLetter.split(',')
              const texts = letters.map(letter => {
                const option = question.options.find(opt => opt.key === letter.trim())
                return option ? option.text : letter
              })
              question.answer = texts.join(',')
            } else {
              // 单选题/判断题：A -> 正确
              const option = question.options.find(opt => opt.key === correctAnswerLetter)
              question.answer = option ? option.text : correctAnswerLetter
            }
          }
        })
        
        
        // 标记为已提交，禁用所有题目和提交按钮
        this.isSubmitted = true
        
        this.showResultDialog = true
        
      } catch (error) {
        this.$message.error('提交试卷失败')
      }
    },
    calculateScore() {
      this.correctCount = 0
      let totalScore = 0
      
      this.quiz.questions.forEach((question, index) => {
        const userAnswer = this.answers[index]
        const isCorrect = this.checkAnswer(userAnswer, question.answer, question.type)
        
        if (isCorrect) {
          this.correctCount++
          totalScore += question.score
        }
      })
      
      this.score = totalScore
    },
    checkAnswer(userAnswer, correctAnswer, type) {
      // 不再使用此方法，改为从 wrongQuestions 列表判断
      return false
    },
    isCorrect(index) {
      const question = this.quiz.questions[index]
      // 从错题列表中判断：如果不在错题列表中，说明答对了
      if (!this.wrongQuestions || this.wrongQuestions.length === 0) {
        return true // 没有错题，全对
      }
      return !this.wrongQuestions.some(wq => wq.id === question.id)
    },
    formatAnswer(answer) {
      if (!answer) return '-'
      
      if (Array.isArray(answer)) {
        return answer.join(', ')
      }
      
      // 如果答案是逗号分隔的字符串（多选题），保持原样
      if (typeof answer === 'string' && answer.includes(',')) {
        return answer
      }
      
      return answer
    },
    getUserAnswerText(index, question) {
      const answer = this.answers[index]
      if (!answer) return '-'
      
      // 多选题：数组格式 ["A", "B"]
      if (Array.isArray(answer)) {
        const texts = answer.map(key => {
          const option = question.options.find(opt => opt.key === key)
          return option ? option.text : key
        })
        return texts.join(', ')
      }
      
      // 单选题/判断题：字符串格式 "A"
      const option = question.options.find(opt => opt.key === answer)
      return option ? option.text : answer
    },
    returnToCourse() {
      // 清除定时器
      if (this.timer) {
        clearInterval(this.timer)
      }
      // 跳转回课程详情
      this.$router.push(`/course/${this.courseId}`)
    }
  }
}
</script>

<style scoped>
.quiz-page {
  padding: 20px 0;
}

.quiz-header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 16px;
}

.title-section {
  flex: 1;
  min-width: 250px;
}

.title-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.quiz-title {
  font-size: 20px;
  font-weight: bold;
  color: #304156;
  margin: 0;
}

.quiz-meta {
  font-size: 13px;
  color: #86909C;
  margin: 0;
}

.timer-section {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background-color: #F5F7FA;
  border-radius: 20px;
  font-size: 14px;
}

.timer-text {
  font-weight: 500;
  color: #304156;
}

.timer-text.warning {
  color: #F53F3F;
}

.nav-card {
  margin-bottom: 20px;
}

.nav-title {
  font-size: 13px;
  font-weight: 500;
  color: #304156;
  margin: 0 0 12px 0;
}

.question-nav {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.nav-button {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  border: 1px solid #E5E6EB;
  background-color: #F5F7FA;
  color: #606266;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  outline: none;
}

.nav-button:hover {
  border-color: #165DFF;
  color: #165DFF;
}

.nav-button.active {
  background-color: #165DFF;
  border-color: #165DFF;
  color: #ffffff;
}

.nav-button.answered:not(.active) {
  background-color: #E8F9F0;
  border-color: #00B42A;
  color: #00B42A;
}

.question-card {
  margin-bottom: 20px;
}

.question-container {
  min-height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.question-item {
  flex: 1;
}

.question-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.question-badge {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #E8F3FF;
  color: #165DFF;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  font-weight: 500;
  margin-right: 12px;
  margin-top: 2px;
  flex-shrink: 0;
}

.question-info {
  flex: 1;
}

.question-title {
  font-size: 15px;
  font-weight: 500;
  color: #304156;
  margin: 0 0 4px 0;
  line-height: 1.6;
}

.question-meta {
  font-size: 13px;
  color: #86909C;
  margin: 0;
}

.options-container {
  margin-top: 16px;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.option-label {
  display: block;
  padding: 12px 16px;
  border: 1px solid #E5E6EB;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.option-label:hover {
  border-color: #165DFF;
  background-color: #F7F8FA;
}

.option-radio,
.option-checkbox {
  width: 100%;
  margin: 0;
}

.option-radio >>> .el-radio__label,
.option-checkbox >>> .el-checkbox__label {
  width: 100%;
  white-space: normal;
  line-height: 1.6;
}

.question-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 24px;
  margin-top: 24px;
  border-top: 1px solid #E5E6EB;
  flex-wrap: wrap;
  gap: 16px;
}

.nav-buttons {
  display: flex;
  gap: 12px;
}

.confirm-content {
  text-align: center;
  padding: 20px 0;
}

.confirm-icon {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background-color: #E8F3FF;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 16px;
}

.confirm-icon i {
  font-size: 32px;
  color: #165DFF;
}

.confirm-title {
  font-size: 18px;
  font-weight: bold;
  color: #304156;
  margin: 0 0 8px 0;
}

.confirm-message {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.result-content {
  padding: 20px 0;
}

.result-summary {
  text-align: center;
  margin-bottom: 24px;
}

.score-circle {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 96px;
  height: 96px;
  border-radius: 50%;
  background-color: #E8F9F0;
  margin-bottom: 16px;
}

.score-number {
  font-size: 32px;
  font-weight: bold;
  color: #00B42A;
}

.score-unit {
  font-size: 14px;
  color: #00B42A;
  margin-left: 4px;
}

.result-message {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.result-stats {
  padding: 16px;
  background-color: #F5F7FA;
  border-radius: 8px;
  margin-bottom: 16px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.stat-row:last-child {
  margin-bottom: 0;
}

.stat-label {
  font-weight: 500;
  color: #304156;
}

.stat-value {
  color: #606266;
}

.toggle-details {
  text-align: center;
  padding: 16px 0;
  border-top: 1px solid #E5E6EB;
  border-bottom: 1px solid #E5E6EB;
}

.toggle-details .el-icon-arrow-down {
  transition: transform 0.3s;
}

.toggle-details .el-icon-arrow-down.rotate {
  transform: rotate(180deg);
}

.answer-details {
  margin-top: 16px;
}

.detail-item {
  border: 1px solid #E5E6EB;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 16px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-header {
  padding: 12px 16px;
  background-color: #F5F7FA;
  font-weight: 500;
  color: #304156;
}

.detail-body {
  padding: 16px;
}

.detail-question {
  font-weight: 500;
  margin-bottom: 12px;
  color: #304156;
}

.detail-answer {
  margin: 0 0 8px 16px;
}

.user-answer {
  color: #606266;
}

.user-answer.correct {
  color: #00B42A;
}

.user-answer.wrong {
  color: #F53F3F;
}

.answer-explanation {
  margin-top: 16px;
  padding: 12px;
  background-color: #F5F7FA;
  border-radius: 8px;
}

.explanation-title {
  font-size: 13px;
  font-weight: 500;
  margin: 0 0 4px 0;
  color: #304156;
}

.explanation-text {
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

/* 弹窗响应式样式 */
.result-dialog >>> .el-dialog {
  margin: 5vh auto !important;
}

.result-dialog >>> .el-dialog__body {
  max-height: calc(85vh - 120px);
  overflow-y: auto;
  padding: 20px;
}

.answer-details {
  max-height: 400px;
  overflow-y: auto;
  padding-right: 8px;
}

.answer-details::-webkit-scrollbar {
  width: 6px;
}

.answer-details::-webkit-scrollbar-track {
  background: #F5F7FA;
  border-radius: 3px;
}

.answer-details::-webkit-scrollbar-thumb {
  background: #C9CDD4;
  border-radius: 3px;
}

.answer-details::-webkit-scrollbar-thumb:hover {
  background: #86909C;
}

@media (max-width: 1024px) {
  .result-dialog >>> .el-dialog {
    margin: 3vh auto !important;
  }
  
  .result-dialog >>> .el-dialog__body {
    max-height: calc(90vh - 120px);
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
  }

  .timer-section {
    width: 100%;
    justify-content: center;
  }

  .question-footer {
    flex-direction: column;
    align-items: stretch;
  }

  .nav-buttons {
    width: 100%;
    justify-content: space-between;
  }

  .question-footer > .el-button {
    width: 100%;
  }
  
  .result-dialog >>> .el-dialog__body {
    padding: 16px;
    max-height: calc(92vh - 100px);
  }
  
  .answer-details {
    max-height: 300px;
  }
  
  .score-circle {
    width: 80px;
    height: 80px;
  }

  .score-number {
    font-size: 28px;
  }
}
</style>